package com.seeyon.apps.ndk.kit;

import com.seeyon.cap4.form.bean.*;
import com.seeyon.cap4.form.modules.engin.base.formData.CAP4FormDataManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.ModuleType;
import com.seeyon.ctp.common.authenticate.domain.User;
import com.seeyon.ctp.common.content.mainbody.CtpContentAllBean;
import com.seeyon.ctp.common.content.mainbody.MainbodyService;
import com.seeyon.ctp.common.content.mainbody.MainbodyStatus;
import com.seeyon.ctp.common.content.mainbody.MainbodyType;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.log.CtpLogFactory;
import com.seeyon.ctp.common.po.content.CtpContentAll;
import com.seeyon.ctp.util.DateUtil;
import com.seeyon.ctp.util.UUIDLong;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;

import java.sql.Timestamp;
import java.util.Map;

public class FormCap4Kit {

    private static final Log log = CtpLogFactory.getLog(FormCap4Kit.class);

    private static CAP4FormDataManager cap4FormDataManager = (CAP4FormDataManager) AppContext.getBean("cap4FormDataManager");


    /**
     * 添加无流程表单数据
     *
     * @param formDataMasterBean 表单主数据
     * @param formBean           表单数据
     */
    public static void addUnFlowFormDataCap4(FormDataMasterBean formDataMasterBean, FormBean formBean) {
        try {
            // 获取当前用户ID
            User user = AppContext.getCurrentUser();
            Long userId = null;
            if (user != null) {
                userId = user.getId();
            }
            if (userId == null) {
                userId = formBean.getCreatorId();
            }
            // 获取表单权限视图数据
            FormAuthViewBean formAuthViewBean = formBean.getNewFormAuthViewBeans().get(0);
            // 获取权限视图数据ID
            String rightid = String.valueOf(formAuthViewBean.getId());
            // 插入或更新表单主数据
            cap4FormDataManager.insertOrUpdateMasterData(formDataMasterBean);
            // 获取主数据ID
            Long masterId = formDataMasterBean.getId();
            // 正文内容保存
            int moduleType = getModuleTypeCap4(formBean);
            MainbodyService mainBodyService = MainbodyService.getInstance();
            // 获取正文内容
            CtpContentAll ctpContentAll = mainBodyService.getContent(moduleType, masterId);
            // 保存正文内容
            ctpContentAll = saveContentAllForFormCap4(ctpContentAll, masterId, userId, formBean, rightid);
            // 保存或更新正文内容
            mainBodyService.saveOrUpdateContentAll(ctpContentAll);
        } catch (Exception e) {
            log.error("新增无流程表单数据报错信息:", e);
        }
    }


    /**
     * 保存表单Cap4的CtpContentAll信息
     *
     * @param ctpContentAll 保存的CtpContentAll对象
     * @param masterId      主键ID
     * @param userid        用户ID
     * @param formBean      表单Bean对象
     * @param rightId       权限ID
     * @return 保存后的CtpContentAll对象
     * @throws BusinessException 无应用绑定时抛出该异常
     */
    private static CtpContentAll saveContentAllForFormCap4(CtpContentAll ctpContentAll, long masterId, long userid, FormBean formBean, String rightId) throws BusinessException {
        Timestamp timestamp = DateUtil.currentTimestamp();
        if (ctpContentAll != null) {
            ctpContentAll.setModifyId(userid);
            ctpContentAll.setModifyDate(timestamp);
            return ctpContentAll;
        }
        CtpContentAllBean content = new CtpContentAllBean();
        FormBindBean bindBean = formBean.getBind();
        if (bindBean != null) {
            content.setModuleTemplateId(bindBean.getId());
            Map<String, FormBindAuthBean> bindAuth = bindBean.getUnFlowTemplateMap();
            if (CollectionUtils.isEmpty(bindAuth.values())) {
                throw new BusinessException("无应用绑定");
            }
            for (FormBindAuthBean authBean : bindAuth.values()) {
                content.setTitle(authBean.getName());
            }
        }
        content.setModuleType(getModuleTypeCap4(formBean));
        content.setCreateId(userid);
        content.setCreateDate(timestamp);
        content.setSort(0);
        content.setId(UUIDLong.longUUID());
        content.setStatus(MainbodyStatus.STATUS_POST_SAVE);
        content.setContentType(Integer.valueOf(MainbodyType.FORM.getKey()));
        content.setContentTemplateId(formBean.getId());
        content.setContentDataId(masterId);
        content.setModuleId(masterId);
        content.setModifyDate(timestamp);
        content.setModifyId(userid);
        content.setRightId(rightId);
        return content.toContentAll();
    }

    /**
     * 根据表单类型获取模块类型
     *
     * @param formBean 表单Bean对象
     * @return 模块类型
     * @throws BusinessException 业务异常
     */
    private static int getModuleTypeCap4(FormBean formBean) throws BusinessException {
        int moduleType = 0;
        if (formBean.getFormType() == 6) {
            moduleType = ModuleType.cap4UnflowForm.getKey();
        }
        if (moduleType == 0) {
            log.warn("无效表类型");
            throw new BusinessException("内容保存失败");
        }
        return moduleType;
    }
}
